<template>
  <div class="login">
    <div class="form">
      <h3 class="title">用户登录</h3>
      <el-form :model="ruleForm"
               status-icon
               :rules="rule"
               ref="ruleForm"
               label-width="55px">
        <el-form-item label="邮箱"
                      prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="密码"
                      prop="password">
          <el-input type="password"
                    v-model="ruleForm.password"></el-input>
        </el-form-item>
        <div class="btn">
          <el-form-item>
            <el-button type="primary"
                       @click="submitForm">提交</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </div>
      </el-form>
      <p class="register">还没有账户?前往 <span @click="register">注册</span></p>
    </div>
  </div>
</template>

<script>
import jwt_decode from "jwt-decode";
export default {
  name: "login",
  data () {
    return {
      ruleForm: {
        email: "",
        password: "",
      },
      rule: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    isEmpty (value) {
      return (
        value == undefined || value == null ||
        (typeof value == "object" && Object.keys(value).length == 0) ||
        (typeof value == "string" && value.trim().length == 0)
      )
    },
    submitForm () {
      this.$axios.post("http://localhost:5000/api/users/login", this.ruleForm).then(res => {
        console.log(1);
        // 将用户token存储到本地存储
        localStorage.setItem("userToken", res.data.token);

        // 解析token
        const decode = jwt_decode(res.data.token);
        // console.log(decode);
        this.$store.commit("getUser", decode);
        let isAuthorization = true;
        this.$store.commit("getAuthorization", isAuthorization);


        // 存储到vuex
        // this.$store.dispatch("setAuthorization", !this.isEmpty(decode));
        // this.$store.dispatch("setUser", decode);

        this.$message({
          message: '登录成功!正在返回首页页!',
          type: 'success'
        });
        setTimeout(() => {
          this.$router.push("/content")
        }, 1200);
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields();
    },
    register () {
      this.$router.push("/register");
    }
  }
}

</script>

<style scoped>
.login {
  width: 95%;
  height: 100%;
  margin: 0 auto;
}
.title {
  text-align: center;
}
.form {
  padding: 10px;
}
.btn {
  text-align: center;
  margin-right: 55px;
}
.register {
  text-align: center;
}
.register span {
  color: #507daf;
  cursor: pointer;
}
.register span:hover {
  color: #0b58b0;
}
</style>